<?php
/**
 * Created by PhpStorm.
 * User: louis
 * Date: 2023/1/12
 * Time: 11:55
 */

namespace App\Services\Pay\Alipay;


use App\Models\Member\AlipayTransferLog;
use App\Services\Com\UtilService;
use Yansongda\LaravelPay\Facades\Pay;
use Yansongda\Pay\Exceptions\Exception;

class PayService
{
    /**
     * 支付宝转账到个人支付宝
     * @param $trans_amount
     * @param $order_title
     * @param $identity
     * @param $name
     * @return bool
     * @throws \Exception
     */
    public static function transfer($trans_amount, $order_title, $identity, $name, $memberUuid=''){
        try {
            $payService = Pay::alipay();

            $order = [
                'out_biz_no' => UtilService::uniqid(),
                'trans_amount' => $trans_amount,
                'product_code' => 'TRANS_ACCOUNT_NO_PWD',//销售产品码。单笔无密转账固定为 TRANS_ACCOUNT_NO_PWD。
                'biz_scene' => 'DIRECT_TRANSFER', //业务场景。单笔无密转账固定为 DIRECT_TRANSFER。
                'order_title' => $order_title, //转账业务的标题，用于在支付宝用户的账单里显示。
                'payee_info' => [
                    'identity' => $identity,
                    'identity_type' => 'ALIPAY_LOGON_ID',
                    'name' => $name,
                ],
            ];

            $result = $payService->transfer($order);

            AlipayTransferLog::create([
                'member_uuid' => $memberUuid,
                'trans_amount' => $trans_amount,
                'order_title' => $order_title,
                'identity' => $identity,
                'name' => $name,
                'result' => json_encode($result),
            ]);

            if($result->status != 'SUCCESS') throw new \Exception($result->msg);
        }catch (Exception $e){
            throw new \Exception(isset($e->raw['alipay_fund_trans_uni_transfer_response']['sub_msg']) ? $e->raw['alipay_fund_trans_uni_transfer_response']['sub_msg'] : $e->getMessage());
        }

        return true;
    }
}